package com.aabte.springcloudstudy.ribbonconsumer;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Slf4j
@RequestMapping
@RestController
public class ConsumerController {

    @Resource
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "addFallBack")
    @RequestMapping(path = "/add", method = RequestMethod.GET)
    public Integer add(@RequestParam(name = "a") Integer a, @RequestParam(name = "b") Integer b) {
        log.info("start ConsumerController#add.");
        ResponseEntity<Integer> responseEntity = restTemplate.getForEntity("http://provider-service/add?a={1}&b={2}", Integer.class, a, b);
        Integer result = responseEntity.getBody();
        log.info("End ConsumerController#add. result: {}", result);
        return result;
    }

    public Integer addFallBack(Integer a, Integer b) {
        log.warn("Start addFallBack. a: {}, b: {}", a, b);
        Integer mockResult = -1;
        log.warn("End addFallBack. mockResult: {}", mockResult);
        return mockResult;
    }
}